#include "commands.h"
#include "common.h"
#include "serialization.h"
#include <iostream>

using namespace std;

namespace commands
{

std::string typeOnlyCommand(Command c)
{
    genericCommand cc;
    cc.addType(c);
    return cc.serialize();
}


AddFile::AddFile(string username, int fileSize, string filename) : username(username), fileSize(fileSize), filename(filename)
{
    type = ADD_FILE;

}

AddFile::AddFile(std::string str) // unserialize
{
    std::istringstream iss(str);
    int t;
    iss >> t;
    type = (Command)t;
    iss >> fileSize;

    username = Unserialize(iss);
    filename = Unserialize(iss);
    LOG << type << " " << endl;
    LOG << "username = " << username << endl;
    LOG << "filesize = " << fileSize << endl;
    LOG << "filename = " << filename << endl;

}

std::string AddFile::serialize()
{
    stringstream ss;
    ss << type;
    ss << ' ' << fileSize;
    ss << Serialize(username);
    ss << Serialize(filename);
    return ss.str();
}


Checkout::Checkout(string username, string filename) : username(username), filename(filename)
{
    type = CHECKOUT;
}

Checkout::Checkout(std::string str) // unserialize
{
    std::istringstream iss(str);
    int t;
    iss >> t;
    type = (Command)t;

    username = Unserialize(iss);
    filename = Unserialize(iss);
    LOG << type << " " << endl;
    LOG << "username = " << username << endl;
    LOG << "filename = " << filename << endl;

}

std::string Checkout::serialize()
{
    stringstream ss;
    ss << type;
    ss << Serialize(username);
    ss << Serialize(filename);
    return ss.str();
}


BeginUpload::BeginUpload(int port) : port(port), type(BEGIN_UPLOAD)
{
}

BeginUpload::BeginUpload(string str) // unserialize
{
    istringstream iss(str);
    int t;
    iss >> t;
    type = (Command)t;
    iss >> port;

    LOG << "type = " << type << endl;
    LOG << "port = " << port << endl;
}

string BeginUpload::serialize()
{
    stringstream ss;
    ss << type;
    ss << " ";
    ss << port;
    return ss.str();
}

AskForDownload::AskForDownload(int fileSize) : fileSize(fileSize), type(ASK_FOR_DOWNLOAD)
{
}

AskForDownload::AskForDownload(string str) // unserialize
{
    istringstream iss(str);
    int t;
    iss >> t;
    type = (Command)t;
    iss >> fileSize;

    LOG << "type = " << type << endl;
}

string AskForDownload::serialize()
{
    stringstream ss;
    ss << type;
    ss << " ";
    ss << fileSize;
    return ss.str();
}

std::string genericCommand::getString(bool &ok)
{
    std::string s = Unserialize(ss);
    ok = !ss.fail();
    return s;
}

std::string genericCommand::getString()
{
    bool b;
    return getString(b);
}


}
